package com.ecloud.scheduler.config;

import com.ecloud.common.util.PropUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Properties;

/**
 * @author Squbi
 */
@Configuration
public class SchedulerConfig {

    @Autowired
    JobFactory jobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(
            SchedulerProperties schedulerProperties,
            SchedulerThreadPoolProperties threadPoolProperties
    ) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        Properties prop = new Properties();
        prop = PropUtil.joinProp(prop, schedulerProperties.toProperties());
        prop = PropUtil.joinProp(prop, threadPoolProperties.toProperties());

        prop.put("org.quartz.jobStore.misfireThreshold", "60000");
        //表示 quartz 中的所有数据，比如作业和触发器的信息都保存在内存中（而不是数据库中）
        prop.put("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");

        factory.setQuartzProperties(prop);
        //
        factory.setJobFactory(jobFactory);
        factory.setSchedulerName("ContextScheduler");
        // 延时10s启动 目的是多服务同时启动时 确保依赖的服务优先启动完成
        factory.setStartupDelay(10);
        factory.setApplicationContextSchedulerContextKey("applicationContextKey");
        // 设置自动启动，默认为true
        factory.setAutoStartup(true);
        return factory;
    }
}
